import xtend from 'xtend';

import {
  getSblxBySbzlx
} from '../../../../mapUtils/SblxUtil';
import {
  parse
} from '../../../../mapUtils/Geojson2WktUtil';
import {
  projectLngLatToWebMercator
} from '../../../../mapUtils/CoordinateUtil';
import {
  randomUUID
} from '../../../../mapUtils/RandomUtil';
import CONST from '../../../../constant/Common';

const DRAW_SOURCES = {
  HOT: 'sgmap-draw-hot',
  COLD: 'sgmap-draw-cold'
};

/**
 * 电网设备修改接口
 * @interface
 */
class Ipms {
  constructor(_tool) {
    this.tool = _tool;
    this.gridTool = _tool.gridTool;
    this.isEdit = false;
    this.isDrawEnd = false;
    this._updateHandle = this.updateHandle.bind(this);
    // 所有回调，都可以重写
    this.events = {
      onDrawEnd: () => {},
      onKeyDown: () => {},
      onVerificationCallback: () => {},
      onDelete: () => {},
      onReset: () => {}
    };
    //加双击事件的目的是双击的时候取消单击事件
    this._processEvents = {
      onClick: this._onClick.bind(this),
      onDblClick: this._onDblClick.bind(this),
      onKeyDown: this._onKeyDown.bind(this)
    };
    this.drawtype = '';
    this.mode = '';
    // 捕捉的信息
    this.snaps = null;
    this.geometry = null;
    this.features = null;
    this.properties = {
      drawid: randomUUID()
    };
  }

  /**
   * 获取地图对象
   */
  getMap() {
    return this.tool.getMap();
  }

  /**
   * 获取工具箱
   * @param {String} toolname 工具箱名称
   */
  getTool(name) {
    return this.tool.getTool(name);
  }

  /**
   * 获取服务接口
   */
  getApi() {
    return this.tool.getApi();
  }

  /**
   * 获取事件总线
   */
  getEventBus() {
    return this.tool.getEventBus();
  }

  /**
   * 新增电网设备
   * @param {*} mode 编辑模式
   * @param {Array} snapList 捕捉图形
   * @param {Array} ignoreSbzlx 捕捉图形中不包含该数组中设备子类型设备
   */
  draw(mode, snapList, ignoreSbzlx) {
    this.isEdit = false;
    this.mode = mode;
    this.getTool('EditTool').changeMode(mode, this);
    this.getTool('EditTool').enableSnap();
    if (ignoreSbzlx) {
      if (snapList) {
        this.getTool('EditTool').setSnapFeatures(snapList.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
      } else {
        this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
      }
    } else {
      this.getTool('EditTool').setSnapFeatures(snapList || this.getTool(this.gridTool).getRenderedFeatures().features);
    }
    this.getTool('EditTool').setEvents({
      onCreate: this._updateHandle,
      onUpdate: this._updateHandle
    });
    if (!snapList) {
      this.getTool(this.gridTool).events.datachange = () => {
        if (ignoreSbzlx) {
          this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
        } else {
          this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features);
        }
      };
    }
    return this;
  }

  /**
   * 编辑
   * @param {*} mode 编辑模式
   * @param {feature} feature 编辑对象
   * @param {Array} snapList 捕捉图形
   * @param {Array} ignoreSbzlx 捕捉图形中不包含该数组中设备子类型设备
   */
  edit(mode, feature, snapList, ignoreSbzlx) {
    this.isEdit = true;
    this.mode = mode;
    this.getTool('EditTool').editFeatures([feature]);
    this.getTool('EditTool').changeMode(this.mode, {
      featureIds: [feature.id]
    });
    this.getTool('EditTool').enableSnap();
    if (ignoreSbzlx) {
      if (snapList) {
        this.getTool('EditTool').setSnapFeatures(snapList.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
      } else {
        this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
      }
    } else {
      this.getTool('EditTool').setSnapFeatures(snapList || this.getTool(this.gridTool).getRenderedFeatures().features);
    }
    this.getTool('EditTool').setEvents({
      onCreate: this._updateHandle,
      onUpdate: this._updateHandle
    });
    if (!snapList) {
      this.getTool(this.gridTool).events.datachange = () => {
        if (ignoreSbzlx) {
          this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features.filter(item => !(ignoreSbzlx.indexOf(Number(item.properties.sbzlx)) > -1)));
        } else {
          this.getTool('EditTool').setSnapFeatures(this.getTool(this.gridTool).getRenderedFeatures().features);
        }
      };
    }
    return this;
  }

  /**
   * 停止
   */
  stop() {
    // 重置绘图工具
    this.getTool('EditTool').reset();
    this._removeProcessEvents();
  }

  /**
   * 重新开始绘制
   */
  restart() {
    this.isDrawEnd = false;
    // 移除事件
    this.getTool('EditTool').setEvents({
      onCreate: null,
      onUpdate: null
    });
    // 更改模式
    this.getTool('EditTool').trash();
    this.getTool('EditTool').changeMode(this.mode, this);
    // 添加事件
    this.getTool('EditTool').setEvents({
      onCreate: this._updateHandle,
      onUpdate: this._updateHandle
    });
  }

  /**
   * 修改完成后调用
   */
  async drawEnd() {
    console.log('drawEnd');
    // 调用回调函数
    let data = await this.getTargetDevice();
    console.log('data', data);
    console.log('this.events.onDrawEnd', this.events.onDrawEnd);
    if (this.events.onDrawEnd) {
      this.events.onDrawEnd({
        geometry: this.getGeometry(),
        snaps: this.snaps,
        data: data
      });
    }
  }

  /**
   * 验证完成后调用
   * @param {RuleResult} ruleResult
   */
  verificationCallback(ruleResult) {
    // 调用回调函数
    if (this.events.onVerificationCallback) {
      this.events.onVerificationCallback(ruleResult);
    }
  }

  /**
   * 修改完成
   * @param {*} e 修改后的数据
   */
  updateHandle(e) {
    this.isDrawEnd = true;
    this.features = e.features;
    // 设置当前绘制的图形
    this.geometry = e.features[0].geometry;
    let snaps = e.features[0].properties.snaps;
    if (Array.isArray(snaps)) {
      // 如果绘制的是线
      snaps.forEach((snap) => {
        if (snap && snap.layer) {
          snap.layer.properties.sblx = getSblxBySbzlx(snap.layer.properties.sbzlx);
        }
      });
      this.snaps = snaps.map((snap) => snap && snap.layer);
    } else {
      // 如果绘制的是点
      if (snaps && snaps.layer) {
        snaps.layer.properties.sblx = getSblxBySbzlx(snaps.layer.properties.sbzlx);
      }
      this.snaps = snaps ? snaps.layer : null;
    }
  }

  /**
   * 获取设备坐标
   */
  getGeometry() {
    return this.geometry;
  }

  /**
   * 获取WKT格式坐标数据
   */
  getGeometryWkt(geometry) {
    if (geometry) {
      let _geo = {};
      if (typeof geometry === 'string') {
        _geo = JSON.parse(geometry);
      } else {
        _geo = JSON.parse(JSON.stringify(geometry));
      }
      _geo.coordinates = projectLngLatToWebMercator(_geo.coordinates);
      return parse(_geo);
    }
    return null;

  }

  /**
   * 获取当前绘制设备信息
   */
  async getTargetDevice() {}

  /**
   * 启用捕捉功能
   */
  enableSnap() {
    this.getTool('EditTool').enableSnap();
  }

  /**
   * 设置捕捉图形
   * @param {features} features 捕捉图形坐标
   */
  setSnapFeatures(features) {
    this.getTool('EditTool').setSnapFeatures(features);
  }

  /**
   * 设置图层式样
   * @param {*} layerConfig 图层式样
   * @param {*} type 图层类型
   * @ignore
   */
  _setupLayerConfig(layerConfig, type) {
    var newLayerConfig = xtend({}, layerConfig, {
      id: layerConfig.id + '.' + type,
      source: type === 'hot' ? DRAW_SOURCES.HOT : DRAW_SOURCES.COLD
    });
    if (!this.getMap().getSource(newLayerConfig.source)) {
      this.getMap().addSource(newLayerConfig.source, {
        type: 'geojson',
        data: {
          type: 'FeatureCollection',
          features: []
        }
      });
    }
    if (!this.getMap().getLayer(newLayerConfig.id)) {
      this.getMap().addLayer(newLayerConfig);
    }
  }

  /**
   * 获取绘制图形
   * @ignore
   */
  _getDrawingFeature() {
    var all = this.getTool('EditTool').getAll();
    // console.log(all, "from get drawing feature");
    return all.features.find((feature) => feature.properties.drawid === this.properties.drawid);
  }

  /**
   * 获取虚拟节点
   * @ignore
   */
  async _getVirtualPoint(point, line, sbzlx) {
    // 用捕捉点将线路切割
    let newLines = turf.lineSplit(line, point).features;
    // 用捕捉点坐标替换切割线路的首位坐标（第一条线的终点坐标，第二条线的终点坐标）
    let coordinates1 = newLines[0].geometry.coordinates;
    let coordinates2 = newLines[1].geometry.coordinates;
    coordinates1[coordinates1.length - 1] = point.geometry.coordinates;
    coordinates2[0] = point.geometry.coordinates;
    // 生成虚拟节点
    let data = {
      startEquip: {
        sblx: line.properties.sblx,
        sbzlx: line.properties.sbzlx,
        shape: this.getGeometryWkt(newLines[0].geometry)
      },
      endEquip: {
        sblx: line.properties.sblx,
        sbzlx: line.properties.sbzlx,
        shape: this.getGeometryWkt(newLines[1].geometry)
      },
      schema: this.option.schema,
      ghrw: this.option.ghrw || '',
      ghfa: this.option.ghfa || '',
      ghnf: this.option.ghnf || '',
      ghxm: this.option.ghxm || '',
      fxlx: this.option.fxlx || 2,
      otherfields: {
        // eslint-disable-next-line camelcase
        tjd_shape: this.getGeometryWkt(point.geometry),
        // eslint-disable-next-line camelcase
        tjd_sbzlx: sbzlx,
        // eslint-disable-next-line camelcase
        yxl_oid: line.properties.oid,
        // eslint-disable-next-line camelcase
        yxl_sbzlx: line.properties.sbzlx,
        // eslint-disable-next-line camelcase
        yxl_versionid: line.properties.versionid
      }
    };
    // eslint-disable-next-line camelcase
    let {
      resp_code,
      datas
    } = await this.getApi().PwghGhsjTxfw.sbjh.post_sbjh_addTjd({
      params: {
        verRule: CONST.verRule
      },
      data: data
    });
    // eslint-disable-next-line camelcase
    if (resp_code === 200) {
      return datas;
    }
    return null;
  }

  /**
   * 添加绘制过程事件
   * @ignore
   */
  _addProcessEvents() {}

  /**
   * 移除绘制过程事件
   * @ignore
   */
  _removeProcessEvents() {}

  /**
   * 鼠标单击事件
   * @ignore
   */
  _onClick() {}

  /**
   * 鼠标双击事件
   * @ignore
   */
  _onDblClick() {}

  /**
   * 键盘按键事件
   * @ignore
   */
  _onKeyDown() {}

  /**
   * 验证点合理性
   * @ignore
   */
  async _ruleJudgePoint() {}

  /**
   * 是否是电站
   * @param {Number} sbzlx 设备子类型
   * @ignore
   */
  _isStation(sbzlx) {
    // 30000099 300000 t_fz_znyc_dz 水电站
    // 30000003 300000 t_fz_znyc_dz 发电厂
    // 30000010 300000 t_fz_znyc_dz 太阳能电厂
    // 30000002 300000 t_fz_znyc_dz 风电厂
    // 34300000 300000 t_fz_znyc_dz 用户变电站
    // 30000006 300000 t_fz_znyc_dz 用户站
    // 30000001 300000 t_fz_znyc_dz 换流站
    // return [
    //     30000099,
    //     30000003,
    //     30000010,
    //     30000002,
    //     34300000,
    //     30000006,
    //     30000001,
    //     30000000
    // ].indexOf(sbzlx * 1)>=0;
    return sbzlx == 30000000

  }

  /**
   * 是否是线路
   * @param {Number} sbzlx 设备子类型
   * @ignore
   */
  _isLine(sbzlx) {
    return sbzlx * 1 === 10100000 || sbzlx * 1 === 20100000;
  }

  /**
   * 是否是虚拟节点
   * @param {Number} sbzlx 设备子类型
   * @ignore
   */
  _isVirtualPoint(sbzlx) {
    return sbzlx * 1 === 62000001 || sbzlx * 1 === 62000002;
  }

  /**
   * 查询变电站是否有可用间隔
   * @param {Object} param 变电站参数
   * @param {Number} connDydj 连接设备电压等级
   * @ignore
   */
  async _isDzjgAvailable({
    oid,
    sbzlx
  }, connDydj) {
    let res = await this.getApi().PwghGhsjTxfw.sbjh.get_sbjh_findConnec({
      params: {
        schema: this.option.schema,
        ghrw: this.option.ghrw || '',
        ghfa: this.option.ghfa || '',
        ghxm: this.option.ghxm || '',
        fxlx: this.option.fxlx || 2,
        oid: oid,
        sbzlx: sbzlx,
        dydj: connDydj,
        verRule: CONST.verRule
      }
    });
    return res.datas;
  }

  /**
   * 查询虚拟点是否和架空线路相连
   * @param {*} param 查询参数
   * @ignore
   */
  async _isTempPointConnJkxl({
    oid,
    sbzlx
  }) {
    let res = await this.getApi().PwghGhsjTxfw.sbjh.get_sbjh_findXndSfLjJkx({
      params: {
        schema: this.option.schema,
        ghrw: this.option.ghrw || '',
        ghfa: this.option.ghfa || '',
        ghnf: this.option.ghnf || '',
        ghxm: this.option.ghxm || '',
        fxlx: this.option.fxlx || 2,
        oid: oid,
        sbzlx: sbzlx,
        verRule: CONST.verRule
      }
    });
    return res.datas;
  }

  /**
   * 查询虚拟点是否和电力电缆相连
   * @param {*} param 查询参数
   * @ignore
   */
  async _isTempPointConnDldl({
    oid,
    sbzlx
  }) {
    let res = await this.getApi().PwghGhsjTxfw.sbjh.get_sbjh_findXndSfLjdxd({
      params: {
        schema: this.option.schema,
        ghrw: this.option.ghrw || '',
        ghfa: this.option.ghfa || '',
        ghnf: this.option.ghnf || '',
        ghxm: this.option.ghxm || '',
        fxlx: this.option.fxlx || 2,
        oid: oid,
        sbzlx: sbzlx,
        verRule: CONST.verRule
      }
    });
    return res.datas;
  }
}

export default Ipms;